/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.menuItem;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.BaseObject;
import com.blandware.atleap.model.core.ContentImage;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.service.core.MenuManager;
import com.blandware.atleap.service.core.RoleManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.MenuItemForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Updates menu item
 * </p>
 * <p><a href="UpdateMenuItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.47 $ $Date: 2008/04/29 17:48:09 $
 * @struts.action path="/core/menuItem/update"
 * name="menuItemForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-menuItem-update"
 * @struts.action-forward name="inputForward"
 * path=".core.menuItem.update"
 * @struts.action-forward name="viewMenuItem"
 * path="/core/menuItem/view.do"
 * redirect="true"
 * @struts.action-forward name="listMenuItems"
 * path="/core/menuItem/list.do"
 * redirect="false"
 * @struts.action-forward name="callUpdateMenuItem"
 * path="/core/menuItem/callUpdate.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/menuItem/list.do"
 */
public final class UpdateMenuItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setAttribute("linkTargets", WebappConstants.LINK_TARGETS);

		MenuItemForm menuItemForm = (MenuItemForm) form;
		Long ownerId;
		if ( !GenericValidator.isBlankOrNull(menuItemForm.getOwnerId()) ) {
			ownerId = Long.valueOf(menuItemForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		Long menuItemId;
		if ( !GenericValidator.isBlankOrNull(menuItemForm.getId()) ) {
			menuItemId = Long.valueOf(menuItemForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing menu item ID. Returning to list");
			}
			return mapping.findForward("listMenuItems");
		}

		if ( !isCancelled(request) ) {

			MenuManager menuManager = (MenuManager) getBean(Constants.MENU_MANAGER_BEAN);
			MenuItem menuItem = menuManager.retrieveMenuItem(menuItemId);

			if ( menuItem == null ) {
				// menu item not found. it might be deleted by someone else
				ActionMessages errors = new ActionMessages();
				errors.add("menuItemNotFound", new ActionMessage("core.menuItem.errors.notFound"));
				saveErrors(request, errors);
				return mapping.findForward("listMenuItems");
			}

			if ( menuItem != null && (menuItem.isRedefinition() || !menuItem.isDynamic() || !menuItem.getOwner().getId().equals(ownerId)) ) {
				// cannot update this item
				if ( log.isWarnEnabled() ) {
					log.warn("Tried to update item, which is hardcoded or defined on another layer. It is prohibited. Returning to list.");
				}
				return mapping.findForward("listMenuItems");
			}

			// create refs
			List linkedPages = new ArrayList();
			List linkedResources = new ArrayList();
			List roles = null;
			boolean titleIsSet = WebappUtil.hasCorrectValues(menuItemForm.getTitleMap());
			String image = menuItemForm.getImage();
			BaseObject linkedObject = WebappUtil.lookupObject(image, request.getSession().getServletContext(), request.getContextPath(), request);
			if ( linkedObject != null && linkedObject instanceof ContentImage ) {
				linkedResources.add(linkedObject);
			}

			String altImage = menuItemForm.getAltImage();
			if ( !GenericValidator.isBlankOrNull(altImage) && !altImage.equals(image) ) {
				linkedObject = WebappUtil.lookupObject(menuItemForm.getAltImage(), request.getSession().getServletContext(), request.getContextPath(), request);
				if ( linkedObject != null && linkedObject instanceof ContentImage ) {
					linkedResources.add(linkedObject);
				}
			}

			linkedObject = WebappUtil.lookupObject(menuItemForm.getLocation(), request.getSession().getServletContext(), request.getContextPath(), request);
			if ( linkedObject != null ) {
				// set external location flag
				menuItem.setExternalLocation(Boolean.FALSE);
				if ( linkedObject instanceof ContentResource ) {
					ContentResource resource = (ContentResource) linkedObject;
					roles = new ArrayList(resource.getRoles());
					linkedResources.add(resource);
				} else if ( linkedObject instanceof Page ) {
					Page page = (Page) linkedObject;
					linkedPages.add(page);

					// set roles
					if ( page instanceof ContentPage ) {
						ContentPage cp = (ContentPage) page;
						roles = new ArrayList(cp.getRoles());
					} else if ( page instanceof ActionPage ) {
						ActionPage ap = (ActionPage) page;
						String[] roleNames = WebappUtil.getAPRoleNames(ap.getUri(), request);
						roles = new ArrayList();
						RoleManager roleManager = (RoleManager) getBean(Constants.ROLE_MANAGER_BEAN);
						for ( int i = 0; i < roleNames.length; i++ ) {
							String roleName = roleNames[i];
							Role role = roleManager.retrieveRole(roleName);
							if ( role != null ) {
								roles.add(role);
							} else {
								// can it happen?
								if ( log.isWarnEnabled() ) {
									log.warn("Role with name '" + roleName + "', specified for Action with URI '" + ap.getUri() + "' could not be found. Skipped.");
								}
							}
						}
					}
				}
			} else {
				// set external location flag
				menuItem.setExternalLocation(Boolean.TRUE);
			}

			if ( !titleIsSet ) {
				// title must be specified
				ActionMessages errors = new ActionMessages();
				errors.add("title", new ActionMessage("core.commons.errors.required", getMessage(request, "core.menuItem.form.title")));
				saveErrors(request, errors, false);
				saveToken(request);
				return mapping.getInputForward();
			}

			Long parentItemId = null;
			if ( menuItem.getParentItem() != null ) {
				parentItemId = menuItem.getParentItem().getId();
			}

			try {

				menuItem.setLinkedResources(linkedResources);
				menuItem.setLinkedPages(linkedPages);
				menuItem.setRoles(roles);

				WebappUtil.copyProperties(menuItem, menuItemForm, request);
                WebappUtil.fillFieldValueWithDefaultLocaleValue(menuItemForm.getTitleMap(), menuItem.getTitle(), servlet.getServletContext());
                menuItem.setTitle(menuItemForm.getTitleMap());
                WebappUtil.copyFieldValue(menuItem.getToolTip(), menuItemForm.getToolTipMap());

                // set to null properties related only to hard-coded elements
				menuItem.setAnchor(null);
				menuItem.setAction(null);
				menuItem.setForward(null);
				menuItem.setOnmouseover(null);
				menuItem.setOnmouseout(null);
				menuItem.setOnclick(null);

				// set to default properties which were not specified in form
				if ( GenericValidator.isBlankOrNull(menuItemForm.getStyle()) ) {
					menuItem.setStyle(null);
				}

				if ( GenericValidator.isBlankOrNull(menuItemForm.getStyleClass()) ) {
					menuItem.setStyleClass(null);
				}

				if ( GenericValidator.isBlankOrNull(menuItemForm.getAlign()) ) {
					menuItem.setAlign(null);
				}

				if ( GenericValidator.isBlankOrNull(menuItemForm.getImage()) ) {
					menuItem.setImage(null);
				}

				if ( GenericValidator.isBlankOrNull(menuItemForm.getAltImage()) ) {
					menuItem.setAltImage(null);
				}

				menuManager.updateMenuItem(menuItem, parentItemId, ownerId);
			} catch ( ObjectOptimisticLockingFailureException e ) {
				// menuItem was updated or deleted by another transaction
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.menuItem.errors.updateFailed"));
				saveErrors(request, errors);
				return mapping.findForward("callUpdateMenuItem");
			}

		}

		// flush cache
		CacheUtil cacheUtil = CacheUtil.getInstance(request);
		cacheUtil.flushMenuCache();
		cacheUtil.flushContentPageCache();

		if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
			String redirectUrl = (String) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
            request.getSession().removeAttribute(WebappConstants.REDIRECT_URL_KEY);
            return new ActionForward(redirectUrl, true);
		}

		return mapping.findForward("listMenuItems");
	}
}